import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

typedef void EventCallback(args,args2);


class FlutterPluginDemo2{
  static const MethodChannel _channel = MethodChannel('flutter_plugin_demo2');

  static const EventChannel? _eventChannel = EventChannel("flutter_show_alert/event");

  static EventCallback? callBack;

  StreamSubscription<dynamic>? _streamSubscription;

  // 方法1：初始化构造方法设置监听内容(统一分发)
  FlutterPluginDemo2(){
    _streamSubscription =  _eventChannel?.receiveBroadcastStream().listen((event) {
      final Map<dynamic,dynamic> map = event;
      String? key = map["key"];
      int? value = map["value"];
      print("handle on ---$key---$value");
      if(map["key"] == "changeVoice"){
        callBack!(key,0);
      }
      else if(map["key"] == "getCount") {
        callBack!(key,value);
      }
    },onError: errorEventListen,onDone:doneEventListen,) as StreamSubscription;

    // WidgetsBinding.instance!.addObserver(this);
  }

  errorEventListen(Object obj) {
    final Object e = obj;
    print("错误打印为------$obj");
    throw e;
  }

  doneEventListen() {
    print("flutter响应完成------");
  }

  static void listener(EventCallback tempCallback) {
    callBack = tempCallback;
  }



  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  static Future<String?> get originalAllData async {
    final String? originalStr = await _channel.invokeMethod('originalAllData');
    return originalStr;
  }

  static Future<String?> sendParamsToOriginal(int key,String value) async {
    Map params = {
      "key":key,
      "value":value,
    };
    final String? count = await _channel.invokeMethod('sendParamsToOriginal',params);
    return count;
  }

  static Future<String?> sendOriginalToHandle(String key,int value) async {
    Map params = {
      "key":key,
      "value":value,
    };
    final String? count = await _channel.invokeMethod('sendOriginalToHandle',params);
    return count;
  }
}
